package com.example.helloandroid;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketReceive implements Runnable {

	private ServerSocket serverSocket;
	private int port;

	public SocketReceive(int port) {
		this.port = port;

	}

	public void run() {

		try {
			serverSocket = new ServerSocket(this.port);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		Socket clientSocket = null;

		while (true) {

			try {

				clientSocket = serverSocket.accept();
				System.out.println("Main siger: Client connected");

				ois = new ObjectInputStream(clientSocket.getInputStream());

				oos = new ObjectOutputStream(clientSocket.getOutputStream());

				String receive = (String) ois.readObject();

				String[] command = receive.split(" = ");
				// System.out.println("Command: " + command[0]);

				String[] para = command[1].split(",");
				// System.out.println("Parameter der kom med: " + para[0]);

				if (command[0].equalsIgnoreCase("alert")) {
					System.out.println(para[0]);
				}

				if (command[0].equalsIgnoreCase("sms")) {
					if (para[0].equalsIgnoreCase("15555215556")) {
						para[0] = "Henning";
					}
					System.out.println("Sms fra: " + para[0] + "\nBesked: \n" + para[1]);
					//Main.send("GIVEMEOST = hej,hej");
				}

				if (command[0].equalsIgnoreCase("GIVEMEOST")) {
					System.out.println("Serveren har modtaget OST "  + para[0]);
				} else {
					oos.writeObject("Tekst er modtaget men er ikke genkendt som en command. \n teksten var: " + receive);
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					oos.close();
					ois.close();
					clientSocket.close();
					System.out.println("Main siger: Client Lukket");

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

	}

}
